﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ByHand.Model;
using ByHand.Services.Code;
using ByHand.Services.Interfaces;
using SmallJob.Services.Code;

namespace FrontEnd.Controllers
{
    public class ProductController : Controller
    {
        //
        // GET: /Product/
        private readonly IProductService _ProductService;

        private readonly IProviderService _ProviderService;
        private readonly IProductOptionService _ProductOptionService;
        private readonly IUserService _UserService;
        private readonly ILogService _LogService;

        public ProductController(IProductService ProductService, IProviderService ProviderService, IProductOptionService ProductOptionService, IUserService UserService, ILogService LogService)
        {
            _ProductService = ProductService;
            _ProviderService = ProviderService;
            _ProductOptionService = ProductOptionService;
            _UserService = UserService;
            _LogService = LogService;
        }
        public ActionResult Index(string shop, string name, string refid, string id, string tempId, string reflocation)
        {
            int pid = 0;
            try
            {
                pid = Convert.ToInt16(name.Split('-')[name.Split('-').Length - 1]);
            }
            catch
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error", "Error404");
            }
            if (!string.IsNullOrWhiteSpace(refid))
            {
                HttpCookie cookie = new HttpCookie("byhandrefid");
                cookie.Value = refid;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                HttpCookie cookie2 = new HttpCookie("enablepopup");
                cookie2.Value = Convert.ToString(true);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie2);
                var userlog = "";
                if (User.Identity.IsAuthenticated) userlog = User.Identity.Name;
                var isbuttonshared = (!string.IsNullOrWhiteSpace(reflocation));
                var log = new Log()
                {
                    OrderID = 0,
                    ProductID = Convert.ToInt32(id),
                    Location = isbuttonshared ? reflocation : Request.UrlReferrer.ToString(),
                    UserType = "Nặc danh",
                    ByHandName = userlog,
                    DateTime = DateTime.Now,
                    RefID = refid
                };
                if (string.IsNullOrWhiteSpace(tempId))
                {
                    tempId = Utility.GenerateId();
                    log.ActionType = (int)ELogActionType.Link_Click;
                    log.ActionDetail = (int)ELogActionDetail.None;
                    log.UserName = tempId;
                }
                else
                {
                    log.ActionType = (int)ELogActionType.Button_Frame_Click;
                    log.ActionDetail = (int)ELogActionDetail.None;
                    log.UserName = tempId;
                }
                _LogService.Add(log);
                HttpCookie cookie4 = new HttpCookie("previouslocation");
                cookie4.Value = log.Location;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie4);

                HttpCookie cookie3 = new HttpCookie("tempId");
                cookie3.Value = tempId;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie3);

                return RedirectPermanent("/Home/Index");
            }
            var cookierefid = Request.Cookies["byhandrefid"];
            var refidvalue = "0";
            if (cookierefid != null)
            {
                refidvalue = cookierefid.Value;
            }
            else
            {
                HttpCookie cookie = new HttpCookie("byhandrefid");
                cookie.Value = refidvalue;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
            var isenablepopup = Request.Cookies["enablepopup"];
            if (isenablepopup != null && Convert.ToBoolean(isenablepopup.Value))
            {
                ViewData["callpopup"] = "true";
                Response.Cookies["enablepopup"].Value = Convert.ToString(false);
            }
            var temID = Request.Cookies["tempId"];
            if (temID != null)
            {
                ViewData["tempId"] = temID.Value;
                if (string.IsNullOrWhiteSpace(temID.Value) || temID.Value.Equals("0"))
                {
                    ViewData["tempId"] = Utility.GenerateId();
                }
            }
            var p = _ProductService.GetById(pid);
            if (p == null)
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error", "Error404");
            }
            var nameCheck = StringHanding.ConvertUrl(p.Title) + '-' + p.ID;
            if (nameCheck != name)
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error", "Error404");
            }
            p.Provider = _ProviderService.GetById(p.ProviderID);
            var shopCheck = StringHanding.ConvertUrl(p.Provider.Name);
            if (shop != shopCheck)
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error", "Error404");
            }
            ViewData["options"] = _ProductOptionService.GetByProductID(p.ID);
            //ViewData["framebtn"] = framebtn;
            ViewData["refid"] = refidvalue;
            if (TempData["ResultPayment"] != null)
            {
                ViewData["ResultPayment"] = TempData["ResultPayment"];
            }
            if (User.Identity.IsAuthenticated)
            {
                ViewData["User"] = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
                ViewData["userid"] = (_UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name)).ID;
            }
            return View("_Show", p);
        }

    }
}
